package com.ethink.platform.controller.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.framework.common.web.BaseController;
import com.ethink.framework.common.web.context.SPRequestContextHolder;
import com.ethink.framework.common.web.response.CommonResponse;
import com.ethink.mdm.api.component.MdmComponent;
import com.ethink.order.api.PurchaseOrderFacade;
import com.ethink.order.api.SaleDemandOrderFacade;
import com.ethink.order.api.enums.SaleDemandOrderOrderStatusEnum;
import com.ethink.order.api.info.PurchaseOrderDetailInfo;
import com.ethink.order.api.info.SaleDemandOrderDetailInfo;
import com.ethink.order.api.info.SaleDemandOrderInfo;
import com.ethink.order.api.info.SaleDemandOrderModeInfo;
import com.ethink.order.api.request.*;
import com.ethink.order.api.response.SaleConfirmPurchaseResponse;
import com.ethink.order.api.response.SaleDemandOrderAddResponse;
import com.ethink.order.api.response.SaleDemandOrderDetailResponse;
import com.ethink.platform.common.properties.PlatformCommonProperties;
import com.ethink.platform.controller.order.info.ExportInfo;
import com.ethink.platform.manager.ExportManager;
import com.ethink.platform.manager.PublicManager;
import com.ethink.platform.manager.SaleDemandManager;
import com.ethink.system.api.SystemTodoFacade;
import com.ethink.system.api.enums.SystemTodoTodoTypeEnum;
import com.ethink.system.api.request.SystemTodoAddRequest;
import com.ethink.warehouse.api.component.WarehouseComponent;
import com.ethink.warehouse.api.info.MateSkuStockInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 销售需求单 Controller
 *
 * @author default
 * @date 2022-10-31
 */
@Tag(name = "SaleDemandOrderController", description = "销售需求单 Controller")
@RestController
@Slf4j
@RequestMapping("platform-server/v1/order-service")
public class SaleDemandOrderController extends BaseController {

    @Autowired
    private SaleDemandOrderFacade saleDemandOrderFacade;

    @Autowired
    private PurchaseOrderFacade purchaseOrderFacade;

    @Autowired
    private SaleDemandManager saleDemandManager;

    @Autowired
    private WarehouseComponent warehouseComponent;

    @Autowired
    private SystemTodoFacade systemTodoFacade;

    @Autowired
    private PlatformCommonProperties commonProperties;

    @Autowired
    private ExportManager exportManager;

    @Autowired
    private PublicManager publicManager;

    @Operation(summary = "销售需求单分页查询")
    @GetMapping("/saleDemandOrder/query")
    public CommonResponse<List<SaleDemandOrderInfo>> querySaleDemandOrder(SaleDemandOrderQueryRequest request) {
        return succeedWithPage(saleDemandOrderFacade.querySaleDemandOrder(request));
    }

    @Operation(summary = "销售需求单导出")
    @GetMapping("/saleDemandOrder/export")
    public CommonResponse<ExportInfo> exportSaleDemandOrder(SaleDemandOrderQueryRequest request) {
        return succeedWith(exportManager.exportSaleDemandOrder(request));
    }

    @Operation(summary = "销售需求单货品模式分页查询")
    @GetMapping("/saleDemandOrder/queryMode")
    public CommonResponse<List<SaleDemandOrderModeInfo>> querySaleDemandOrderMode(SaleDemandOrderQueryModeRequest request) {
        return succeedWithPage(saleDemandOrderFacade.querySaleDemandOrderMode(request));
    }

    @Operation(summary = "销售需求单货品模式导出")
    @GetMapping("/saleDemandOrder/exportMode")
    public CommonResponse<ExportInfo> exportSaleDemandOrderMode(SaleDemandOrderQueryModeRequest request) {
        return succeedWith(exportManager.exportSaleDemandOrderMode(request));
    }

    @Operation(summary = "详情查询")
    @GetMapping("/saleDemandOrder/get/{orderNo}")
    public CommonResponse<SaleDemandOrderDetailResponse> getSaleDemandOrderById(@PathVariable("orderNo") String orderNo) {
        SaleDemandOrderDetailResponse response = saleDemandOrderFacade.getSaleDemandOrderByNo(orderNo);
        List<String> mateSku = CollUtil.getFieldValues(response.getItem(), "mateSku", String.class);
        //库存数,在途数走实时查询
        Map<String, MateSkuStockInfo> map = warehouseComponent.queryMateSkuStore(mateSku);
        for (SaleDemandOrderDetailInfo demandOrderDetailInfo : response.getItem()) {
            MateSkuStockInfo mateSkuStockInfo = map.get(demandOrderDetailInfo.getMateSku());
            demandOrderDetailInfo.setTotalQty(mateSkuStockInfo == null ? 0 : mateSkuStockInfo.getTotalQty());
            demandOrderDetailInfo.setPurchasingQty(mateSkuStockInfo == null ? 0 : mateSkuStockInfo.getPurchasingQty());
        }
        return succeedWith(response);
    }

    @Operation(summary = "新增")
    @PostMapping("/saleDemandOrder/add")
    public CommonResponse addSaleDemandOrder(@Validated @RequestBody SaleDemandOrderAddRequest request) {
        request.setCreateUserName(SPRequestContextHolder.getCurrentSystemUserRealName());
        request.setCreateUserCode(SPRequestContextHolder.getCurrentSystemUserLoginName());
        request.setBeginTime(new Date());
        BigDecimal defaultTaxRate = publicManager.getRate(request.getSaleSubChannel() == null ? "Z000" : request.getSaleSubChannel());
        request.setDefaultTaxRate(defaultTaxRate);
        SaleDemandOrderAddResponse response = saleDemandOrderFacade.addSaleDemandOrder(request);
        if (SaleDemandOrderOrderStatusEnum.S2.eq(request.getOrderStatus())) {
            try {
                SystemTodoAddRequest addRequest = new SystemTodoAddRequest();
                addRequest.setRoleName(commonProperties.getSaleConfirmRoleName());
                addRequest.setDataId(response.getOrderNo());
                addRequest.setTodoType(SystemTodoTodoTypeEnum.T1.getIntValue());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("creator", SPRequestContextHolder.getCurrentSystemUserRealName());
                jsonObject.put("saleChannel", request.getSaleChannel());
                jsonObject.put("saleSubChannel", request.getSaleSubChannel());
                jsonObject.put("orderNo", response.getOrderNo());
                addRequest.setTodoMessage(jsonObject.toJSONString());
                systemTodoFacade.addSystemTodo(addRequest);
            } catch (Exception e) {
                log.error("创建待办失败", e);
            }
        }
        return succeed();
    }

    @Operation(summary = "删除")
    @PostMapping("/saleDemandOrder/delete/{saleDemandOrderId}")
    public CommonResponse deleteSaleDemandOrder(@PathVariable("saleDemandOrderId") Long saleDemandOrderId) {
        saleDemandOrderFacade.deleteSaleDemandOrder(saleDemandOrderId);
        return succeed();
    }

    @Operation(summary = "查询采购单信息")
    @GetMapping("/saleDemandDetailOrder/listPurchaseDetailOrder/{detailOrderNo}")
    public CommonResponse<List<PurchaseOrderDetailInfo>> queryPurchaseDetailOrderByDetailOrderNo(@PathVariable("detailOrderNo") String detailOrderNo) {
        List<PurchaseOrderDetailInfo> detailInfos = purchaseOrderFacade.queryPurchaseDetailOrderByDetailOrderNo(detailOrderNo);
        return succeedWith(detailInfos);
    }

    @Operation(summary = "销售需求订单数量确认")
    @PutMapping("/saleDemandOrder/confirm")
    public CommonResponse demandConfirm(@Validated @RequestBody SaleDemandOrderConfirmRequest request) {
        saleDemandOrderFacade.demandConfirm(request);
        try {
            systemTodoFacade.doneSystemTodoByDataId(SystemTodoTodoTypeEnum.T1.getIntValue(), request.getOrderNo());
        } catch (Exception e) {
            log.error("待办关闭失败", e);
        }
        try {
            SaleDemandOrderDetailResponse response = saleDemandOrderFacade.getSaleDemandOrderByNo(request.getOrderNo());
            SaleDemandOrderInfo saleDemandOrderInfo = response.getSaleDemandOrderInfo();
            SystemTodoAddRequest addRequest = new SystemTodoAddRequest();
            addRequest.setRoleName(commonProperties.getPurchaseRoleName());
            addRequest.setTodoType(SystemTodoTodoTypeEnum.T3.getIntValue());
            addRequest.setDataId(request.getOrderNo());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderNo", request.getOrderNo());
            jsonObject.put("saleChannel", saleDemandOrderInfo.getSaleChannel());
            jsonObject.put("saleSubChannel", saleDemandOrderInfo.getSaleSubChannel());
            addRequest.setTodoMessage(jsonObject.toJSONString());
            systemTodoFacade.addSystemTodo(addRequest);
        } catch (Exception e) {
            log.error("生成待办失败", e);
        }
        return succeed();
    }

    @Operation(summary = "需求确认数量修改(未报价状态才能修改)")
    @PutMapping("/saleDemandOrder/updateConfirm")
    public CommonResponse saleDemandUpdateConfirm(@RequestBody SaleDemandOrderUpdateConfirmRequest request) {
        saleDemandOrderFacade.demandConfirmUpdate(request);
        return succeed();
    }

    @Operation(summary = "锁单")
    @PutMapping("/saleDemandDetailOrder/lock")
    public CommonResponse saleDemandLock(@Validated @RequestBody SaleDemandOrderLockRequest request) {
        SaleDemandOrderInfo saleDemandOrderInfo = saleDemandOrderFacade.queryMainByDetailId(request.getId());
        SaleDemandOrderDetailInfo detailInfo = saleDemandOrderFacade.queryDetailByDetailId(request.getId());
        BigDecimal exchangeRate = publicManager.getExchangeRate(saleDemandOrderInfo.getCurrencyCode());
        Map<String, BigDecimal> priceMap = publicManager.saleDemandPriceCal(request.getExceptSalePriceTax(), exchangeRate
                , detailInfo.getTaxRate(),detailInfo.getDiscount());
        request.setExceptSalePriceNoTax(priceMap.get("noTax"));
        request.setExceptSalePriceTaxLocal(priceMap.get("taxLocal"));
        request.setExceptSalePriceNoTaxLocal(priceMap.get("noTaxLocal"));
        saleDemandOrderFacade.lock(request);
        return succeed();
    }

    @Operation(summary = "解单")
    @PutMapping("/saleDemandDetailOrder/unlock/{id}")
    public CommonResponse saleDemandUnlock(@PathVariable("id") Long id) {
        saleDemandOrderFacade.unlock(id);
        return succeed();
    }


    @Operation(summary = "采购确认")
    @PutMapping("/saleDemandOrder/oaPass")
    public CommonResponse saleDemandOaPass(@Validated @RequestBody OAPassRequest request) {
        //获取审批人信息
        request.setAuditUserCode(SPRequestContextHolder.getCurrentSystemUserLoginName());
        request.setAuditUserName(SPRequestContextHolder.getCurrentSystemUserRealName());
        SaleConfirmPurchaseResponse response = saleDemandOrderFacade.oaPass(request);
        //增加代办事项
        List<PurchaseOrderDetailInfo> list = response.getList();
        try {
            for (PurchaseOrderDetailInfo purchaseOrderDetailInfo : list) {
                SystemTodoAddRequest addRequest = new SystemTodoAddRequest();
                addRequest.setUserCode(purchaseOrderDetailInfo.getCreateUserCode());
                addRequest.setUserName(purchaseOrderDetailInfo.getCreateUserName());
                addRequest.setTodoType(SystemTodoTodoTypeEnum.T4.getIntValue());
                addRequest.setDataId(purchaseOrderDetailInfo.getDetailOrderNo());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orderNo", response.getOrderNo());
                addRequest.setTodoMessage(jsonObject.toJSONString());
                systemTodoFacade.addSystemTodo(addRequest);
            }
        } catch (Exception e) {
            log.error("增加待转采购单失败");
        }
        return succeed();
    }

    @Operation(summary = "销售需求更改")
    @PutMapping("/saleDemandOrder/update")
    public CommonResponse saleDemandOrderUpdate(@RequestBody @Validated SaleDemandOrderUpdateRequest request) {
        BigDecimal defaultTaxRate = publicManager.getRate(request.getSaleSubChannel() == null ? "Z000" : request.getSaleSubChannel());
        request.setDefaultTaxRate(defaultTaxRate);
        String orderNo = saleDemandOrderFacade.update(request);
        if (SaleDemandOrderOrderStatusEnum.S2.eq(request.getOrderStatus())) {
            try {
                SystemTodoAddRequest addRequest = new SystemTodoAddRequest();
                addRequest.setRoleName(commonProperties.getSaleConfirmRoleName());
                addRequest.setDataId(orderNo);
                addRequest.setTodoType(SystemTodoTodoTypeEnum.T1.getIntValue());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("creator", SPRequestContextHolder.getCurrentSystemUserRealName());
                addRequest.setTodoMessage(jsonObject.toJSONString());
                systemTodoFacade.addSystemTodo(addRequest);
            } catch (Exception e) {
                log.error("创建待办失败", e);
            }
        }
        return succeed();
    }

    @Operation(summary = "导入")
    @PostMapping("/saleDemandOrder/import")
    public CommonResponse saleDemandMateImport(@RequestParam("file") MultipartFile file
            , @RequestParam("saleSubChannel") String saleSubChannel
            , @RequestParam("currencyCode") String currencyCode) {
        if (StrUtil.isBlank(saleSubChannel) || StrUtil.isBlank(currencyCode)) {
            throw new BusinessException(CommonRespCode.PARAM_ERR, "订单来源或者币种不能为空");
        }
        return succeedWith(saleDemandManager.saleDemandImport(file, saleSubChannel, currencyCode));
    }

    @Operation(summary = "po,备注修改")
    @PutMapping("/saleDemandOrder/updateRemark")
    public CommonResponse saleDemandUpdateRemark(@Validated @RequestBody SaleDemandUpdateRemarkRequest request) {
        saleDemandOrderFacade.updateRemark(request);
        return succeed();
    }
}